package pl.sar.auth.server.ejb.beans.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

import org.apache.log4j.Logger;

import pl.sar.auth.server.ejb.beans.IProjectService;
import pl.sar.auth.server.ejb.entities.Project;
import pl.sar.auth.server.ejb.entities.Project_;
import pl.sar.auth.server.ejb.entities.User;

@Stateless( name = "ProjectBean" )
public class ProjectService implements IProjectService
{

    private static Logger logger = Logger.getLogger( ProjectService.class );

    @PersistenceContext( unitName = "sar-pu" )
    private EntityManager em;

    @Override
    public Long registerProject( String projectName )
    {

        CriteriaBuilder criteriaBuilder = em.getCriteriaBuilder();
        CriteriaQuery< Project > criteriaQuery = criteriaBuilder.createQuery( Project.class );

        Root< Project > root = criteriaQuery.from( Project.class );
        criteriaQuery.select( root ).where( criteriaBuilder.equal( root.get( Project_.name ), projectName ) );

        List< Project > projects = em.createQuery( criteriaQuery ).getResultList();

        // check if project exists or not.
        if( projects.size() == 1 )
        {
            logger.info( "Project " + projectName + " exists." );
            return projects.get( 0 ).getId();
        }
        else
        {

            logger.info( "Registering project '" + projectName + "'." );

            Project newProject = new Project();
            newProject.setName( projectName );
            newProject.setValid(true);
            em.persist( newProject );
            logger.info( "Project '" + projectName + "' registered. " );

            return newProject.getId();
        }

    }

    @Override
    public Collection< User > getProjectUsers( String projectName )
    {
    	logger.info("Getting user list for project " + projectName + " ... ");
    	
    	CriteriaBuilder builder = em.getCriteriaBuilder();
    	CriteriaQuery<Project> criteria = builder.createQuery(Project.class);
    	
    	Root<Project> root = criteria.from(Project.class);
    	
    	criteria.select(root);
    	
    	criteria.where(builder.equal(root.get(Project_.name), projectName));
    	
    	List< Project > projects = em.createQuery( criteria ).getResultList();
    	
    	if(projects.size() == 1)
    	{
    		
    		Project project = projects.get(0);
    		
    		logger.info("Project " + projectName + " has " + project.getUsers().size() + " users." );
    		
    		return project.getUsers();
    	}
    	else
    	{
    		return new ArrayList<User>();
    	}
    }
}
